package com.it.system.course_service.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.it.system.course_service.mapper.CourseMapper;
import com.it.system.course_service.service.CourseService;
import com.it.system.educommonapi.entity.Course;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Map;

@Service
public class CourseServiceImpl extends ServiceImpl<CourseMapper, Course> implements CourseService {

    @Autowired
    private CourseMapper courseMapper;

    @Override
    public List<Course> getAllCourse() {
        return courseMapper.selectAllCourse();
    }

    @Override
    public Course getCourseById(long id) {
        return courseMapper.selectCourseById(id);
    }

    @Override
    public Page<Course> getCourseListPage(long current, long size, Long typeId, Long orientationId,
                                    Long subOrientationId, String keywords, String orderField, String orderType) {
        Page<Course> page = new Page<>(current, size);
        QueryWrapper<Course> queryWrapper = new QueryWrapper<>();
        
        // 添加筛选条件
        if (typeId != null) {
            queryWrapper.eq("type_id", typeId);
        }
        
        if (orientationId != null) {
            queryWrapper.eq("orientation_id", orientationId);
        }
        
        if (subOrientationId != null) {
            // 使用字符串列名而不是方法引用
            queryWrapper.eq("sub_orientation_id", subOrientationId);
        }
        
        // 关键词搜索
        if (StringUtils.hasText(keywords)) {
            queryWrapper.like("course_name", keywords)
                    .or()
                    .like("brief", keywords);
        }
        
        // 排序
        boolean isAsc = "asc".equalsIgnoreCase(orderType);
        String orderStr = isAsc ? "asc" : "desc";
        
        switch (orderField) {
            case "price":
                queryWrapper.orderBy(true, isAsc, "price");
                break;
            case "createTime":
                queryWrapper.orderBy(true, isAsc, "create_time");
                break;
            case "sales":
            default:
                queryWrapper.orderBy(true, isAsc, "sales");
                break;
        }
        
        // 执行查询
        return this.page(page, queryWrapper);
    }
} 